﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
//
//====================================================================================================================================================================
// HTMLJavaScriptRenderWebPart for SharePoint
// Provided as an example best practice - David M. Sterling - david_sterling@sterling-consulting.com
// Sterling International Consulting Group - www.sterling-consulting.com - Architects, Designers, Instructors
// Use at your own risk!
//
// This part provides a replacement for the Content Editor Web Part in enabling you to fly in JavaScript, CSS, XML and HTML into a SharePoint page. More effective
// than the CEWP and provides settings for how the code is rendered. 
//====================================================================================================================================================================
//
namespace HTMLJavaScriptRenderWP.HMTLJSRenderWP
{
    [ToolboxItemAttribute(false)]
    public class HMTLJSRenderWP : WebPart
    {
        //
        #region Web Part Properties (Settable)
        //
        //======================================================================================================================
        /// <summary>
        /// UrlToScriptFileStorage
        /// </summary>
        //----------------------------------------------------------------------------------------------------------------------
        /// <remarks>
        /// Url to the script files
        /// </remarks>
        /// 
        private const string defaultUrlToScriptFileStorage = "";
        private string urlToScriptFileStorage = defaultUrlToScriptFileStorage;
        [Category("File Settings")]
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("Full or Relative URL to the web where file is stored (NO ending slash!) - relative is preferred!. Leave blank for current web site.")]
        [WebDescription("Tool tip: Full or Relative URL to the web where file is stored (NO ending slash!) - relative is preferred!. Leave blank for current web site.")]
        public string UrlToScriptFileStorage
        {
            get
            {
                return urlToScriptFileStorage;
            }
            set
            {
                urlToScriptFileStorage = value;
            }
        }
        //
        //======================================================================================================================
        /// <summary>
        /// StorageLibraryName
        /// </summary>
        //----------------------------------------------------------------------------------------------------------------------
        /// <remarks>
        /// Name of the library storing the Script files
        /// </remarks>
        /// 
        private const string defaultStorageLibraryName = "";
        private string storageLibraryName = defaultStorageLibraryName;
        [Category("File Settings")]
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("Library name where Script File is stored")]
        [WebDescription("Tool tip: Library name where Script File is stored")]
        public string StorageLibraryName
        {
            get
            {
                return storageLibraryName;
            }
            set
            {
                storageLibraryName = value;
            }
        }
        //
        //======================================================================================================================
        /// <summary>
        /// FileNameToRender
        /// </summary>
        //----------------------------------------------------------------------------------------------------------------------
        /// <remarks>
        /// Filename to render
        /// </remarks>
        /// 
        private const string defaultFileNameToRender = "";
        private string fileNameToRender = defaultFileNameToRender;
        [Category("File Settings")]
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("File Name to render (.htm, .html, .js, .txt, etc.)")]
        [WebDescription("Tool tip: File Name to render (.htm, .html, .js, .txt, etc.)")]
        public string FileNameToRender
        {
            get
            {
                return fileNameToRender;
            }
            set
            {
                fileNameToRender = value;
            }
        }
        //
        //======================================================================================================================
        /// <summary>
        /// DoNotUseIFRAME
        /// </summary>
        //----------------------------------------------------------------------------------------------------------------------
        /// <remarks>
        /// DoNotUseIFRAME
        /// </remarks>
        /// 
        private const bool defaultDoNotUseIFRAME = true;
        private bool doNotUseIFRAME = defaultDoNotUseIFRAME;
        [Category("Display Settings")]
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("Do Not use an IFRAME to display (applies to non-JS files); be aware that depending on your site settings, using an IFrame may prompt the user to download!")]
        [WebDescription("ToolTip: Do Not use an IFRAME to display (applies to non-JS files); be aware that depending on your site settings, using an IFrame may prompt the user to download!")]
        public bool DoNotUseIFRAME
        {
            get
            {
                return doNotUseIFRAME;
            }
            set
            {
                doNotUseIFRAME = value;
            }
        }
        //
        //======================================================================================================================
        /// <summary>
        /// FramePixelWidth
        /// </summary>
        //----------------------------------------------------------------------------------------------------------------------
        /// <remarks>
        /// FramePixelWidth
        /// </remarks>
        /// 
        private const string defaultFramePixelWidth = "190";
        private string framePixelWidth = defaultFramePixelWidth;
        [Category("Display Settings")]
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("Frame Pixel Width (i.e. 190, 200, etc. or a percent like 100%)")]
        [WebDescription("Tool tip: Frame Pixel Width (i.e. 190, 200, etc. or a percent like 100%)")]
        public string FramePixelWidth
        {
            get
            {
                return framePixelWidth;
            }
            set
            {
                framePixelWidth = value;
            }
        }
        //
        //======================================================================================================================
        /// <summary>
        /// FrameBorder
        /// </summary>
        //----------------------------------------------------------------------------------------------------------------------
        /// <remarks>
        /// Frameborder setting
        /// </remarks>
        /// 
        private const string defaultFrameBorder = "0";
        private string frameBorder = defaultFrameBorder;
        [Category("Display Settings")]
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [WebDisplayName("Frame Border Type (0 = none or 1 = Window style)")]
        [WebDescription("Tool tip: Frame Border Type (0 = none or 1 = Window style)")]
        public string FrameBorder
        {
            get
            {
                return frameBorder;
            }
            set
            {
                frameBorder = value;
            }
        }
        //
        #endregion
        //
        #region Override Methods
        //
        //==========================================================================================================================================
        // RENDER
        //==========================================================================================================================================
        //
        protected override void Render(HtmlTextWriter writer)
        {
            //
            // Test settings:
            //
            //if (UrlToScriptFileStorage == "")
            //{
            //    writer.Write("HTML-Javascript Render: Url to Storage Library for Scripts is not set; please correct through properties");
            //    return;
            //}
            string OpenToolPaneLink = "<a href=\"javascript:MSOTlPn_ShowToolPane2Wrapper('Edit', this, '" + this.ID + "')\">Open the web part tool pane</a>";
            if (StorageLibraryName == "")
            {
                writer.Write("HTML-Javascript Render: HTML/JS File Storage Library name is not set; please correct through properties - " + OpenToolPaneLink);
                return;
            }
            if (FileNameToRender == "")
            {
                writer.Write("HTML-Javascript Render: Filename to render is not set; please correct through properties - " + OpenToolPaneLink);
                return;
            }
            //
            Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                //
                //--------------------------------------------------------------------------------------------------------------------------------------
                // Get the Site/Web/List:
                //--------------------------------------------------------------------------------------------------------------------------------------
                //
                string UseUrl = "";
                //
                if (UrlToScriptFileStorage.ToLower().IndexOf("http") > -1)
                {
                    UseUrl = UrlToScriptFileStorage;
                    try
                    {
                        SPSite LibStoreSite = new SPSite(UseUrl);
                        try
                        {
                            SPList LibStore = LibStoreSite.OpenWeb().Lists[StorageLibraryName];
                            if (LibStore != null)
                            {
                                CompleteRendering(UseUrl, LibStore, writer);
                            }
                            else
                            {
                                writer.Write("HTML-Javascript Render: Error opening library called " + StorageLibraryName);
                                return;
                            }
                        }
                        catch (Exception ErrIn)
                        {
                            string WhyErr = ErrIn.Message.ToString();
                            writer.Write("HTML-Javascript Render: Error opening library called " + StorageLibraryName + " - message: " + WhyErr);
                            return;
                        }
                    }
                    catch (Exception ErrIn)
                    {
                        string WhyErr = ErrIn.Message.ToString();
                        writer.Write("HTML-Javascript Render: Error opening site with URL set - message: " + WhyErr);
                        return;
                    }
                }
                else
                {
                    SPSite LibStoreSite = SPControl.GetContextSite(Context);
                    string SUrl = LibStoreSite.Url.ToString();
                    if (UrlToScriptFileStorage != "")
                    {
                        UseUrl = SUrl + UrlToScriptFileStorage;
                    }
                    else
                    {
                        UseUrl = SUrl;
                    }
                    try
                    {
                        SPList LibStore = LibStoreSite.OpenWeb().Lists[StorageLibraryName];
                        if (LibStore != null)
                        {
                            CompleteRendering(UseUrl, LibStore, writer);
                        }
                        else
                        {
                            writer.Write("HTML-Javascript Render: Error opening library called " + StorageLibraryName);
                            return;
                        }
                    }
                    catch (Exception ErrIn)
                    {
                        string WhyErr = ErrIn.Message.ToString();
                        writer.Write("HTML-Javascript Render: Error opening library called " + StorageLibraryName + " - message: " + WhyErr);
                        return;
                    }
                }
            });
        }
        //
        #endregion
        //
        #region Methods
        //
        //==========================================================================================================================================
        /// <summary>
        /// CompleteRendering
        /// </summary>
        //==========================================================================================================================================
        /// <param name="UseUrl"></param>
        /// <param name="LibStore"></param>
        /// <param name="writer"></param>
        /// 
        protected void CompleteRendering(string UseUrl, SPList LibStore, HtmlTextWriter writer)
        {
            //
            // Fix up the Url for display:
            //
            string ScriptUrl = UseUrl + "/" + StorageLibraryName + "/" + FileNameToRender;
            //
            string RenderUrl = "";
            bool IsScript = false;
            if (FileNameToRender.ToLower().IndexOf(".js") > -1)
            {
                if (FramePixelWidth == "")
                {
                    RenderUrl += "<table width=\"100%\" ><tr><td style=\"width:100%;\" >";
                    RenderUrl += "<script type=\"text/javascript\" src=\"" + ScriptUrl + "\" ></script>";
                    RenderUrl += "</td></tr></table>";
                    IsScript = true;
                }
                else
                {
                    if (FramePixelWidth.IndexOf("%") > -1)
                    {
                        RenderUrl += "<table width=\"" + FramePixelWidth + "\" ><tr><td style=\"width:100%;\" >";
                        RenderUrl += "<script type=\"text/javascript\" src=\"" + ScriptUrl + "\" ></script>";
                        RenderUrl += "</td></tr></table>";
                        IsScript = true;

                    }
                    else
                    {
                        RenderUrl += "<table width=\"" + FramePixelWidth + "px\" ><tr><td style=\"width:100%;\" >";
                        RenderUrl += "<script type=\"text/javascript\" src=\"" + ScriptUrl + "\" ></script>";
                        RenderUrl += "</td></tr></table>";
                        IsScript = true;
                    }
                }
            }
            else
            {
                RenderUrl = ScriptUrl;
            }
            //
            if (IsScript)
            {
                writer.Write(RenderUrl);
            }
            else
            {
                if (doNotUseIFRAME)
                {
                    writer.Write("<div>");
                    SPQuery GetFileQ = new SPQuery();
                    GetFileQ.Query = "<Where><Eq><FieldRef Name=\"FileLeafRef\" /><Value Type=\"File\">" + FileNameToRender + "</Value></Eq></Where>";
                    SPListItemCollection SPLIC = LibStore.GetItems(GetFileQ);
                    if (SPLIC.Count > 0)
                    {
                        SPListItem AnItem = SPLIC[0];
                        //foreach (SPListItem AnItem in LibStore.Items)
                        //{
                        //    if ((string)AnItem.Name.ToLower() == FileNameToRender.ToLower())
                        //    {
                                long LenOf = AnItem.File.Length;
                                byte[] FileContent = new byte[LenOf];
                                FileContent = AnItem.File.OpenBinary();
                                string ConvertToStr = System.Text.Encoding.UTF8.GetString(FileContent);
                                writer.Write(ConvertToStr);
                        //      break;
                        //    }
                        //}
                    }
                    writer.Write("</div>");
                }
                else
                {
                    string FrameBorderSetting = "0";
                    if (FrameBorder == "0" || FrameBorder == "" || FrameBorder == null)
                    {
                        FrameBorderSetting = "0";
                    }
                    else
                    {
                        FrameBorderSetting = "1";
                    }
                    if (FramePixelWidth == "")
                    {
                        writer.Write("<iframe id=\"DisplayFrame\" width=\"100%\" src=\"" + RenderUrl + "\" scrolling=\"no\" marginheight=\"0\" frameborder=\"" + FrameBorderSetting + "\" ></iframe>");

                    }
                    else
                    {
                        if (FramePixelWidth.IndexOf("%") > -1)
                        {
                            writer.Write("<iframe id=\"DisplayFrame\" width=\"" + FramePixelWidth + "\" src=\"" + RenderUrl + "\" scrolling=\"no\" marginheight=\"0\"  frameborder=\"" + FrameBorderSetting + "\" ></iframe>");

                        }
                        else
                        {
                            writer.Write("<iframe id=\"DisplayFrame\" width=\"" + FramePixelWidth + "px\" src=\"" + RenderUrl + "\" scrolling=\"no\" marginheight=\"0\"  frameborder=\"" + FrameBorderSetting + "\" ></iframe>");
                        }
                    }
                }
            }
        }
        //
        #endregion
        //
    }
    //
    //==============================================================================================================================================
    // Sets Frame/Border Type:
    //==============================================================================================================================================
    //
    public enum FrameBorderType : int
    {
        NoFrame = 0,
        Window = 1
    }
}
